 #include<iostream>
 #include "CTimeLine.h"

CTimeLine:: CTimeLine(){
	m_strName = "";
    m_pNextTimeLine = nullptr;
    m_pPreTimeLine = nullptr;
    m_pFirstTask = nullptr;
}

CTimeLine:: CTimeLine(std::string name){
	m_strName = name; 
    m_pNextTimeLine = nullptr;
    m_pPreTimeLine = nullptr;
    m_pFirstTask = nullptr;
}

CTimeLine :: ~CTimeLine(){
    if (m_pNextTimeLine){
        delete m_pNextTimeLine;
    }
}

void CTimeLine::setName(std::string name){
	m_strName = name;
}

std::string CTimeLine::getName() const{
	return m_strName;
}

	// Chain list
ITimeLine* CTimeLine:: find(std::string name){
	if (m_strName == name) {
		return this;
	}
	else if(m_pNextTimeLine){
		return m_pNextTimeLine->find(name);
	}
	else {
		return nullptr;
	}
}

ITimeLine* CTimeLine:: find(int index){
    ITimeLine *ptr = this;
    if(index == 0)
        return this;
    
    int count = 0;
    while(ptr->getNext()){
        if(index == count)
            return ptr;
        
        count++;
        ptr = ptr->getNext();
    }
    
    return nullptr;
}

int CTimeLine:: add(ITimeLine* newTL){
	ITimeLine* itl = this;
    while(itl->getNext()){
        // if(itl->m_strName == newTL->m_strName)//same name
        //     return 1;
        itl = itl->getNext();
    }
    itl->setNext(newTL);
    newTL->setPre(itl);
    newTL->setNext(nullptr);
    return 0;
}

int CTimeLine::  remove(ITimeLine* tl){
	if(tl){
		if(tl->getPre() == nullptr){
			return 2; // can not delete headptr
		}
		ITimeLine* preTimeLine = tl->getPre();
		ITimeLine* nextTimeLine = tl->getNext();
		preTimeLine->setNext(nextTimeLine);
		delete tl;
		return 0;
	}
	return 1;
}

ITimeLine* CTimeLine:: getNext() const{
    return m_pNextTimeLine;
}

ITimeLine*  CTimeLine::getPre() const{
    return m_pPreTimeLine;
}

void CTimeLine::setNext(ITimeLine* plan){
    m_pNextTimeLine = plan;
}

void CTimeLine::setPre(ITimeLine* plan){
    m_pPreTimeLine = plan;
}

int CTimeLine::addTask(ITask *newTask){
    if (m_pFirstTask) {
        if (!m_pFirstTask->add(newTask))
            return 0;
        else
            return 1;
    }
    else {
        m_pFirstTask = newTask;
        return 0;
    }
}

int CTimeLine::removeTask(ITask* task){
    if (m_pFirstTask)
    {
        if (!m_pFirstTask->remove(task))
            return 0;
        else
            return 1;
    }
    else {
        return -1; // nullptr error
    }
}

ITask* CTimeLine::getTask() const{
    return m_pFirstTask;
}

bool CTimeLine::operator==(ITimeLine& t){
    return t.getName() == m_strName;
}
